package com.yxjx.duoxue.message;
//try_PullToRefresh_map
/**
 * http://blog.163.com/chwei_sunshine/blog/static/194126283201462422019422/
 * 
 */
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.JumpActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.database.YxDataBase;
import com.yxjx.duoxue.datamodel.DMObject;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.my.UserLoginActivity;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.push.PushHelper;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.content.Context;
import android.content.Intent;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MessageListActivity extends BaseActionBarActivity {
	
	public static final int MSG_LOAD_MORE = 1;
	public static final int MSG_REFRESH_ALL = 2;
	// 每次请求的消息数量
	public static final int PAGE_MESSAGE_COUNT = 10;
	// Req
	private static final int REQ_LOGIN_FOR_PUSH_ACTIVITY = 1;
	
	private static final String EXTRA_CLIENT_MESSAGE_ITEM = "EXTRA_CLIENT_MESSAGE_ITEM";
	
	private ArrayList<ClientMessageListDTS> data = new ArrayList<ClientMessageListDTS>();
	private PullToRefreshListView mPullRefreshListView;
	MyAdapter adapter = null;
	private Context mContext;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_message_list);
		customizeActionBarTitle("消息中心");
		
		mContext = this;
		StatHelper.addKVEvent(mContext, "event_my_message_center_open");
		
		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setMode(Mode.BOTH);//设置底部下拉刷新模式
		// 下拉上拉文本：
		ILoadingLayout header = mPullRefreshListView.getLoadingLayoutProxy(true, false);
		ILoadingLayout footer = mPullRefreshListView.getLoadingLayoutProxy(false, true);
		header.setPullLabel("下拉刷新");
		header.setReleaseLabel("放开以刷新");
		header.setRefreshingLabel("正在加载");
		footer.setPullLabel("上拉加载更多");
		footer.setReleaseLabel("放开后开始加载");
		footer.setRefreshingLabel("正在加载");
//		mPullRefreshListView.setMode(Mode.PULL_FROM_START);
		
		//设定下拉监听函数
		mPullRefreshListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				Utils.logd("onPullDownToRefresh");
				String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy(true, false).setLastUpdatedLabel(label);
				// Do work to refresh the list here.
				loadAll();
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				Utils.logd("onPullUpToRefresh");
				loadMore();
			}
		});
		
		// 滑动到底部时，调用自动刷新
		// http://blog.csdn.net/u012573920/article/details/44152815
		
		adapter = new MyAdapter(this);

		actualListView = mPullRefreshListView.getRefreshableView();
		actualListView.setAdapter(adapter);	
		
		actualListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				ClientMessageListDTS item = data.get(arg2 - 1);
				UserLoginResponse ulRsp = UserLoginResponse.getInstance(MessageListActivity.this);
				
				// 标记为已读
				item.setMessageRead(1);
				adapter.notifyDataSetInvalidated();
				
				if (ulRsp == null && isNeedLogin(item)) {
					Intent intent = new Intent(MessageListActivity.this, UserLoginActivity.class);
					intent.putExtra(EXTRA_CLIENT_MESSAGE_ITEM, item);
					startActivityForResult(intent, REQ_LOGIN_FOR_PUSH_ACTIVITY);
				} else {
					pushActivity(item);
				}
				
			}
		});
		loadAll();
		
	}
	
	private void loadAll() {
		showLoading();
		JSONObject param = new JSONObject();
		try {
			param.put("startIndex", 0);
			param.put("count", PAGE_MESSAGE_COUNT);
			param.put("time", "" + System.currentTimeMillis());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		new GetDataTask().execute(param, MSG_REFRESH_ALL);
	}
	
	private void loadMore() {
		JSONObject param = new JSONObject();
		try {
			param.put("startIndex", adapter.getCount());
			param.put("count", PAGE_MESSAGE_COUNT);
			param.put("time", "" + System.currentTimeMillis());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		new GetDataTask().execute(param, MSG_LOAD_MORE);
	}
	
	public static ArrayList<ClientMessageListDTS> requestMessagesList(Context context) {
		JSONObject param = new JSONObject();
		try {
			param.put("startIndex", 0);
			param.put("count", PAGE_MESSAGE_COUNT);
			param.put("time", "" + System.currentTimeMillis());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		ArrayList<ClientMessageListDTS> items = null;
		try {
			items = UserReg.requestMessageList(param, context);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return items;

	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			ArrayList<ClientMessageListDTS> items = (ArrayList<ClientMessageListDTS>) msg.obj;
			switch (msg.what) {
			case MSG_REFRESH_ALL:
				adapter.setData(items);
				Globals.clearNewMessages(getApplicationContext());
				break;
			case MSG_LOAD_MORE:
				adapter.addData(items);
				break;
			default:
				break;
			}
			mPullRefreshListView.onRefreshComplete();
		};
	};
	private ListView actualListView;
	
	private class GetDataTask extends AsyncTask<Object, Void, ArrayList<ClientMessageListDTS>> {

		private int callbackId = -1;
		//后台处理部分
		@Override
		protected ArrayList<ClientMessageListDTS> doInBackground(Object... params) {
			JSONObject param = (JSONObject) params[0];
			callbackId = (Integer) params[1];
			
			try {
				ArrayList<ClientMessageListDTS> items = UserReg.requestMessageList(param, MessageListActivity.this);
				YxDataBase.getInstance(MessageListActivity.this).insertMessagesToDb(items);
				return items;
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (ParseException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<ClientMessageListDTS> result) {
			mHandler.sendMessage(mHandler.obtainMessage(callbackId, result));
			super.onPostExecute(result);
		}
	}
	
	public final class ViewHolder{
		public ImageView img;
		public TextView name;
		public TextView info;
		public TextView createdTime;
	}		
	
	public class MyAdapter extends BaseAdapter{

		private LayoutInflater mInflater;
		
		public MyAdapter(Context context){
			this.mInflater = LayoutInflater.from(context);
		}
		
		public void setData(ArrayList<ClientMessageListDTS> items) {
			if (items != null && items.size() > 0) {
				data = items;
			}
			if (data == null || data.size() == 0) {
				showEmpty();
			} else {
				showList();
				if (items.size() == PAGE_MESSAGE_COUNT) {
//					mPullRefreshListView.setMode(Mode.BOTH);
				} else {
//					mPullRefreshListView.setMode(Mode.PULL_FROM_START);
					showLoadAllTip();
				}
			}
			notifyDataSetChanged();
		}
		
		public void addData(ArrayList<ClientMessageListDTS> items) {
			data.addAll(items);
			if (items != null && items.size() == PAGE_MESSAGE_COUNT) {
//				mPullRefreshListView.setMode(Mode.BOTH);
			} else if (items != null){
//				mPullRefreshListView.setMode(Mode.PULL_FROM_START);
				showLoadAllTip();
			}
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return data == null ? 0 : data.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.item_message_list, null);
				holder.name = (TextView) convertView.findViewById(R.id.title);
				holder.info = (TextView) convertView.findViewById(R.id.desc);
				holder.createdTime = (TextView) convertView.findViewById(R.id.time);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			ClientMessageListDTS item = data.get(position);
			holder.name.setText((String)item.getMessageTitle());
			holder.info.setText((String)item.getMessageContent());
			holder.createdTime.setText(Utils.getTimeStamp(item.getCreatedTime(), "yyyy-MM-dd"));

			updateViewItemAsReaded(convertView, (item.getVisited() || item.getMessageRead() == 1));
			
			return convertView;
		}

	}
	
	private void updateViewItemAsReaded(View view, boolean hasRead) {
		if (view == null) {
			return;
		}
		
		view.findViewById(R.id.title).setSelected(hasRead);
		view.findViewById(R.id.time).setSelected(hasRead);
		view.findViewById(R.id.desc).setSelected(hasRead);
		
	}
	
	private void showLoading() {
		findViewById(R.id.loading).setVisibility(View.VISIBLE);
		findViewById(R.id.empty).setVisibility(View.INVISIBLE);
		findViewById(R.id.list).setVisibility(View.INVISIBLE);
	}
	
	private void showEmpty() {
		findViewById(R.id.empty).setVisibility(View.VISIBLE);
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
		findViewById(R.id.list).setVisibility(View.INVISIBLE);
	}
	
	private void showList() {
		findViewById(R.id.list).setVisibility(View.VISIBLE);
		findViewById(R.id.empty).setVisibility(View.INVISIBLE);
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
	}
	
	public void refresh(View view) {
		Utils.logd("refresh");
		loadAll();
	}
	
	/**
	 * 判断合法的uri
	 * @param item
	 * @return
	 * ［DO]
	 *  Messages 类型: 
	 *  1代金劵页面 app type(duoxueapp)  -----------(Need Login)---
	 *  2专题 H5  title＋url(http)
	 *  [3]活动 app type(duoxueapp)+id 
	 *  [4]课程 app type(duoxueapp)+id 
	 *  [5]学校 app type(duoxueapp)+id
	 *  [6]套餐 app type(duoxueapp)+id <购买按钮>
	 *  [7]订单详情 app type(duoxueapp)+id-----------(Need Login)---
	 *  [8]我的订单 app type-----------(Need Login)---
	 *  
	 *  [NOT DO]
	 *  9课程列表 app type+json // 先不做
	 */
	private boolean isValidUrl(ClientMessageListDTS item) {
		if (item == null || UIHelper.isEmpty(item.getMessageUri())) {
			return false;
		}
		String url = item.getMessageUri();
		// 满足duoxueapp schema或者http地址
		if (url.startsWith(JumpActivity.PREFIX_DATA) || url.startsWith("http")) {
			return true;
		}
		return false;
	}
	
	/**
	 * 是否需要登录
	 * @return
	 */
	private boolean isNeedLogin(ClientMessageListDTS item) {
		if (!isValidUrl(item)) {
			return false;
		}
		String url = item.getMessageUri();
		if (url.endsWith(PushHelper.VALUE_PAGE_MYCOUPON)
				|| url.endsWith(PushHelper.VALUE_PAGE_MYORDERS)
				|| url.contains(PushHelper.TYPE_ORDER_INFO)) {
			return true;
		}
		return false;
	}
	
	@Override
	protected void onActivityResult(int req, int result, Intent data) {
		if (req == REQ_LOGIN_FOR_PUSH_ACTIVITY) {
			if (result == RESULT_OK) {
				ClientMessageListDTS item = (ClientMessageListDTS) data.getSerializableExtra(EXTRA_CLIENT_MESSAGE_ITEM);
				pushActivity(item);
			}
		} else {
			super.onActivityResult(req, result, data);
		}
	}
	
	private void pushActivity(ClientMessageListDTS item) {
		setAsHasRead(item);
		if (!isValidUrl(item)) {
			return;
		}
		PushHelper.pushActivity(this, item2Custom(item));
	}
	
	// 网络请求主要是为了标记已读。
	private void setAsHasRead(final ClientMessageListDTS item) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					JSONObject jo = new JSONObject();
					jo.put("id", "" + item.getId());
					jo.put("time", "" + System.currentTimeMillis());
					YxDataBase.getInstance(getApplicationContext()).markMessageAsChecked(item);
					if (!isValidUrl(item)) {
						return;
					}
					boolean result = UserReg.requestMessageInfo(jo, MessageListActivity.this);
					Utils.logd("message id = " + item.getId() + " has been read? result = " + result);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	private String item2Custom(ClientMessageListDTS item) {
		if (item == null || UIHelper.isEmpty(item.getMessageUri())) {
			return "";
		}
		String url = item.getMessageUri();
		
		if (url.startsWith(JumpActivity.PREFIX_DATA)) {
			//课程，学校，老师，活动，套餐，订单，我的代金劵，我的订单
			JSONObject jo = new JSONObject();
			String[] parseResult = Utils.parseSchema(url);
			if (parseResult == null) {
				return "";
			}
			try {
				jo.put(PushHelper.KEY_TYPE, parseResult[0]);
				jo.put(PushHelper.KEY_TYPE_ID, parseResult[1]);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return jo.toString();
			
		} else if (url.startsWith("http")) {
			// 专题
			JSONObject jo = new JSONObject();
			try {
				jo.put(PushHelper.KEY_TYPE, PushHelper.TYPE_AD);
				jo.put(PushHelper.KEY_URL, item.getMessageUri());
				jo.put(PushHelper.KEY_TITLE, item.getMessageTitle());
				jo.put(PushHelper.KEY_CONTENT, item.getMessageContent());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return jo.toString();
		}
		return "";
	}
	
	
	private void showLoadAllTip() {
		UIHelper.showTips(mPullRefreshListView, "已加载全部");
	}
	
}
